from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
from bs4 import BeautifulSoup
import csv
import os
import cv2
from PIL import Image
import pytesseract
import numpy as np
import sys
import PIL.Image
from pathlib import Path
import ddddocr
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import base64
from selenium.common.exceptions import TimeoutException
import matplotlib.pyplot as plt
from datetime import datetime

# ===== 添加向后兼容性代码 =====
if not hasattr(PIL.Image, 'ANTIALIAS'):
    PIL.Image.ANTIALIAS = PIL.Image.LANCZOS

def login_with_captcha():
    # 配置Chrome选项
    chrome_options = Options()
    # chrome_options.add_argument('--headless')  # 无头模式，如果需要
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')

    # 初始化WebDriver
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)

    # 访问登录页面
    driver.get("https://www.i-elitech.net/user/login")
    time.sleep(2)

    # 账号
    username_input = driver.find_element(By.ID, "userName")
    username_input.clear()
    username_input.send_keys("temp_d121")
    time.sleep(1)

    # 密码
    password_input = driver.find_element(By.ID, "accountPassword")
    password_input.clear()
    password_input.send_keys("D121d121d121@")
    time.sleep(1)

    # 获取验证码图片
    wait = WebDriverWait(driver, 2)
    img = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "verify-code")))

    # 用 JS 将 blob jpg 图片转为 base64
    img_base64 = driver.execute_script("""
            var img = arguments[0];
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, img.width, img.height);
            return canvas.toDataURL('image/jpeg').split(',')[1];
        """, img)

    img_bytes = base64.b64decode(img_base64)
    ocr = ddddocr.DdddOcr()
    result = ocr.classification(img_bytes)

    # 填入验证码输入框
    vercode_input = driver.find_element(By.ID, "verCode")
    vercode_input.clear()
    vercode_input.send_keys(result)
    time.sleep(1)
    # 同意协议
    agree_checkbox = driver.find_element(By.ID, "agree")
    if not agree_checkbox.is_selected():
        agree_checkbox.click()
    time.sleep(1)
    # 点击登录按钮
    login_button = driver.find_element(By.XPATH, "//button[span[text()='登 录']]")
    login_button.click()
    time.sleep(2)
    return driver

def click_element(driver):
    # 点击“在线设备”区域
    online_device_box = driver.find_element(
        By.XPATH, "//div[@class='box']//p[@class='title' and text()='在线设备']/ancestor::div[@class='box']"
    )
    online_device_box.click()
    time.sleep(3)

    # 点击“1030”设备
    device_1030 = driver.find_element(
        By.XPATH, "//span[@class='device-name' and contains(text(), '1030')]/parent::p"
    )
    device_1030.click()
    time.sleep(4)

    # 点击“数据图表”tab
    data_chart_tab = driver.find_element(
        By.XPATH, "//div[@role='tab' and contains(@class, 'ant-tabs-tab') and text()='数据图表']"
    )
    data_chart_tab.click()
    time.sleep(3)

def extract_and_save_temperature_data(driver, CSV_FILE, MD_FILE):


    # 提取HTML
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')

    # 提取 data-row-key 的记录（最多前 10 条）
    records = []
    rows = soup.find_all("tr", class_="ant-table-row")
    for row in rows:
        row_key = row.get("data-row-key")
        if row_key and row_key.isdigit() and int(row_key) < 10:
            cells = row.find_all("td")
            if len(cells) >= 2:
                time_str = cells[0].get_text(strip=True)
                temp_str = cells[1].get_text(strip=True)
                if '℃' in temp_str:
                    records.append((time_str, temp_str))

    # 创建 CSV 文件（如果不存在），写入表头
    if not os.path.exists(CSV_FILE):
        with open(CSV_FILE, "w", newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["时间", "温度"])

    # 读取已有数据
    existing_records = set()
    with open(CSV_FILE, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        next(reader, None)  # 跳过表头
        for row in reader:
            if len(row) >= 2:
                existing_records.add((row[0], row[1]))

    # 写入新数据（只追加新的）
    new_records = [r for r in records if r not in existing_records]
    if new_records:
        with open(CSV_FILE, "a", newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerows(new_records)

    # 读取所有记录
    all_records = []
    with open(CSV_FILE, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        next(reader, None)  # 跳过表头
        for row in reader:
            if len(row) >= 2:
                all_records.append((row[0], row[1]))

    # 按时间正序排序
    all_records = sorted(all_records, key=lambda x: x[0])

    # 绘制温度曲线（只用最新的10条）
    if all_records:
        # 获取最新的10条数据
        latest_records = all_records[-10:] if len(all_records) > 10 else all_records

        dates = []
        temps = []
        for time_str, temp_str in latest_records:
            dates.append(time_str)
            # 提取温度数值（去掉℃符号）
            temp_value = float(temp_str.replace('℃', ''))
            temps.append(temp_value)

        # 创建图表
        plt.figure(figsize=(12, 6))
        plt.plot(dates, temps, marker='o', linestyle='-', color='#1E90FF')
        plt.title('最新10条温度变化曲线', fontsize=16)
        plt.xlabel('时间', fontsize=12)
        plt.ylabel('温度 (℃)', fontsize=12)
        plt.grid(True, linestyle='--', alpha=0.7)
        plt.xticks(rotation=45)
        plt.tight_layout()

        # 保存图表
        chart_path = os.path.join(os.path.dirname(CSV_FILE), 'temperature_chart.png')
        plt.savefig(chart_path)
        plt.close()
        print(f"✅ 温度曲线已保存至 {chart_path}（仅使用最新10条数据）")

    # 按时间倒序排列用于Markdown显示
    all_records = sorted(all_records, key=lambda x: x[0], reverse=True)

    # 写入 Markdown 表格
    markdown_lines = ["| 时间 | 温度 |", "| ---- | ---- |"]
    for time_str, temp_str in all_records:
        markdown_lines.append(f"| {time_str} | {temp_str} |")

    with open(MD_FILE, "w", encoding="utf-8") as f:
        f.write("\n".join(markdown_lines))

    print(f"✅ 写入成功，共 {len(all_records)} 条记录，新增 {len(new_records)} 条")

# 定义CSV和Markdown文件路径
CSV_FILE = r"C:\Users\guozt\Desktop\temperature\temperature_data.csv"       #保存的 CSV 文件路径
MD_FILE = r"C:\Users\guozt\Desktop\temperature\temperature_data.md"         #保存的 Markdown 文件路径

while True:
    driver = login_with_captcha()
    click_element(driver)
    extract_and_save_temperature_data(driver, CSV_FILE, MD_FILE)
    time.sleep(50)
    driver.quit()